import { defineStore } from "pinia";
import request from "@/utils/request";
import {
  IApiRes,
  CategoryListType,
  TopCategory,
  SubCategory,
} from "@/types/data";
import { topCategory } from "@/store/constants";
// topCategory调用map方法
const defaultCategoty = topCategory.map((item) => {
  return {
    name: item,
  };
});

const categoty = defineStore("categoty", {
  state() {
    return {
      list: defaultCategoty as CategoryListType[],
      topCategory: {} as TopCategory,
      subCategory: {} as SubCategory,
    };
  },
  actions: {
    async getCategoryList() {
      const res = await request.get<IApiRes<CategoryListType[]>>(
        "/home/category/head"
      );
      // 目标 给数据加上open属性方便页面进行二级菜单渲染
      res.data.result.forEach((item) => {
        item.open = false;
      });
      this.list = res.data.result;
    },
    show(id: string) {
      const category = this.list.find((item) => item.id === id);
      category!.open = true;
    },
    hide(id: string) {
      const category = this.list.find((item) => item.id === id);
      category!.open = false;
    },
    async getTopCategory(id: string) {
      // const res = await request.get<IApiRes<TopCategory>>("/category", {
      //   params: {
      //     id,
      //   },
      // });
      const res = await request.get<IApiRes<TopCategory>>(`/category?id=${id}`);
      this.topCategory = res.data.result;
    },
    async getSubFilter(id: string) {
      const res = await request.get<IApiRes<SubCategory>>(
        "/category/sub/filter",
        {
          params: {
            id,
          },
        }
      );
      this.subCategory = res.data.result;
    },
  },
  getters: {},
});

export default categoty;
